
<?php

/*

   <svn_trunk>/editAnnotations.php
  
   -- Handles interaction with annotators in support of editing thread
      properties of postnums

*/


// ini_set("display_errors", "On");

require_once('db_php/db_config.php');
require_once('db_php/Threads.php');

//$db = db_connect();

if(!isset($_GET['fileSel'])) {
  $fileno = 1;
  $annotator1 = $annotator2 = 1;
} else {
  $fileno = $_GET['fileSel'];
  $annotator1 = $annotator2 = 1;  // just testing while trying to get
                                  // this to work
  //$annotator1 = $_GET['annotator1Sel'];
}

$params = "filenumber=$fileno&annotator1=$annotator1";

$dataTable = "Data";
$annotationsTable = "Annotations";
$fileTable = "Files";


$annotatorsSql = "select id from annotators";
$annotators = mysql_query($annotatorsSql) 
    or die(__LINE__ . ": Couldn't execute file query." . mysql_error());
$annotatorList = array();

while($row = mysql_fetch_array($annotators, MYSQL_ASSOC)) {
  $annotatorList[] = $row["id"];
}

$annotatorsJSON = json_encode($annotatorList);
$script .= "var annotators=$annotatorsJSON;\n";

$filesToAnnotatorsSql = "select filenumber, annotator 
                         from data, annotations 
                         where data.id=postId group by filenumber,annotator";
$filesToAnnotators = mysql_query($filesToAnnotatorsSql) 
    or die(__LINE__ . ": Couldn't execute file query." . mysql_error());
$fileMap = array();
$file = array();
$no = 0;
while($row = mysql_fetch_array($filesToAnnotators, MYSQL_ASSOC)) {
  $no = $row["filenumber"];
  if(!isset($fileMap[$no])) {
	$fileMap[$no] = array();
  }
  array_push($fileMap[$no], $row["annotator"]); 
}

$filesSql = "select id, name 
             from files 
             where id in (" . implode(",", array_keys($fileMap)) . ")";
$files = mysql_query($filesSql) 
    or die(__LINE__ . ": Couldn't execute file query." . mysql_error());

/*
   $file[] = Array ( id,
                     name,
                     Annotators: Array (Ann_ID) )
*/
while($row = mysql_fetch_array($files, MYSQL_ASSOC)) {
  $file[] = array("name" => $row["name"], 
                  "id" => $row["id"], 
                  "annotators" => $fileMap[$row["id"]]);
}
$fileJSON =  json_encode($file);

$script .= "var fileMap = $fileJSON;\n";

$dataSql = "select threada, threadb, common 
            from threadcomparison 
            where filenumber = $fileno 
               and annotatora = $annotator1 
               and annotatorb = $annotator2";
$data = mysql_query($dataSql) 
    or die(__LINE__ . ": Couldn't execute data query.". mysql_error());

$i=0;
$script .= "var commonPosts = new Array();\n";

/*
   Need to find out what this data represents.
   Currently, it has no returned rows from the query.
   (I verified in mySQL as well).
*/
while($row = mysql_fetch_array($data, MYSQL_ASSOC)) {
        $threada = $row["threada"];
	$threadb = $row["threadb"];
	$common = $row["common"];
	$convertIdQuery = "select group_concat(postnum) as ids 
                           from data where id in ($common)";
	$convertId = mysql_query($convertIdQuery) 
            or die(__LINE__ . ": Couldn't execute data query.") . mysql_error();
	$idRow = mysql_fetch_array($convertId, MYSQL_ASSOC);
	$common = "[" . preg_replace('/(\d+)/', '"$1"', $idRow["ids"]) . "]";
	if(!isset($ts[$threada])) {
		$ts[$threada] = Array();
		$script .= "commonPosts[$threada] = new Array();\n";
	}
	if(!isset($ts[$threada][$threadb])) {
		$ts[$threada][$threadb] = 1;
		$script .= "commonPosts[$threada][$threadb] = new Array();\n";
	}
        $script .= "commonPosts[$threada][$threadb]=$common;\n";
}

// Add the current filenumber and annotator to js vars

$script .= "var filenumber = $fileno;\n";
$script .= "var annotator1 = $annotator1;\n";

/*
   The following lines are to aide in debugging.
   Uncomment any line that contains that var you want to see.
   Keep <pre></pre> uncommented.
*/
echo '<pre>';
// print($dataSql . "\n");
// print($data . "\n");
// print($annotator1 . "\n");
// print_r(implode("\n", split(";", $script)));
echo '</pre>';

?>


<html>
<head>
<link rel="stylesheet" type="text/css" media="screen" href="css/sunny/jquery-ui-1.7.2.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/custom.css" />

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.sprintf.js"></script>
<script type="text/javascript" src="js/dropdown.js"></script>

<script type="text/javascript">
<?php echo $script; ?>
</script>

<script type="text/javascript"> 
        var lastsel;
	var lastsela;
	var lastselb;
        var postWidth = 40;
	var timestampWidth = 70;
	var userWidth = 90;
	var threadWidth = postWidth;
	var relationWidth = threadWidth;

	var threada;
	var threadb;
	var curPosts;

	var mainHeight = 400;
	var threadHeight = 200;

        var primaryDd = '#fileSel';
	var annotator1Dd = '#annotator1Sel';

        // Populate the initial thread tree (as JSON) from ./db_php/Threads.php
        // threadJSON: { "roots"    : [     root1, root2, ..., rootn       ],
        //               "parents"  : {   <post_num> : <post_num_parent>   },
        //               "children" : {   <post_num> : [child1,...,childn] }}
        
        var threadJSON = <?php echo getInitialThreadTree($fileno, 
                                                         $annotator1); ?>;
        
	jQuery().ready(
        function ()
        {  populateSelect($(primaryDd).get(0), 
                          $.map(fileMap, function(f) 
                                      { return { name: f.name, value: f.id} }));
           $(primaryDd).val(<?php echo $fileno?>);
           $(primaryDd).bind('change', 
              function() 
              {  var file = this.value;
	         $.map(annotators, function(an) 
                                   {  $(annotator1Dd).get(0).append
                                      (new Option(an, an));
                                   });
              });
           
           jQuery("#list1").jqGrid(
           {  url:'./event_handlers/getMainJQGridDataEdit.php?' +
                  '<?php echo $params;?>', 
	      datatype: "json", 
	      colNames:
                 ['Post ID','Timestamp', 'Sys', 'User', 'Content','Parent',
                  'Relation','Thread'],
	      colModel:
                 [{name:'ID',index:'postnum', width:postWidth,}, 
		  {name:'Time',index:'timestamp', width:timestampWidth},
		  {name:'Sys',index:'system', width:1},
		  {name:'User',index:'user', width:userWidth}, 
		  {name:'Content',index:'content', width:500, 
                         formatter:colorThread}, 
		  {name:'Parent',index:'parent', width:postWidth, 
                         editable:true, edittype:'text'}, 
		  {name:'Relation',index:'relation', 
                        width:relationWidth,align:"right", 
                        editable:true, edittype:'text'}, 
		  {name:'Thread',index:'thread', width:threadWidth}, ], 
              onSelectRow: 
                 function(id)
                 {  var linea, lineb;
		    var posa, posb;
		    var graphHeight;
      		    if(id && id!==lastsel)
                    {  alert(lastsel);
        	       jQuery('#list1').restoreRow(lastsel);
        	       jQuery('#list1').editRow(lastsel, false);
        	       jQuery('#list1').editRow(id,true);
                       threada = jQuery('#list1').jqGrid('getCell', id, 
                                                         'Thread');
		       //curPosts = commonPosts[threada][threada];
		       urla = $.sprintf("getThread.php?file=%d&thread \
                                         =%d&annotator=%d", filenumber, 
                                         threada, 1);
                       linea = $.sprintf("#%s-%s", id, 1);
                       lastsel=id;
                       jQuery('#annotator1').setGridParam(
                                             {url:urla}).trigger("reloadGrid");
                       graphHeight = jQuery('#annotator1').getGridParam(
                                                           'height');
		       alert(jQuery(linea).position()['top']);
                       jQuery('#gbox_annotator1 .ui-jqgrid-bdiv').scrollTop(
                          jQuery(linea).position()['top'] - graphHeight/2);
      		    }
    	         },
              afterInsertRow: 
                 function(id)  
                 {  if(jQuery('#list1').jqGrid('getCell', id, 'Sys') == 1) 
                    { jQuery('#list1').jqGrid('setRowData', id, 'false', 
                              "system");
                    }
                 },
              afterSaveCell:
                 function(r_id, cname, value, iRow, iCol)
                 {
                 },
              afterSubmitCell:
                 function(response, r_id, cellname, value, iRow, iCol)
                 {  var responseJSON = JSON.parse(response.responseText);
                    var retThreadJSON = JSON.parse(responseJSON.threadJSON);
                    var errors = responseJSON.errors;
                    if(errors != '')  return [false, errors];
                    else              
                    {  threadJSON = retThreadJSON; return [true, ""];  }
                 },
              beforeSubmitCell:
                 function(r_id, cname, value, iRow, iCol)
                 {  return {"annotator1":annotator1,
                            "filenumber":filenumber,
                            "threadJSON":JSON.stringify(threadJSON)};
                 },
              onCellSelect:
                 function(r_id, iCol, cellcontent)
                 {  
                 },
              errorCell:
                 function(response, status)
                 {  alert(response.responseText + ", " + status);
                 },
              // jsonreader: { userdata: "userdata", },
	      height: mainHeight,
	      rowNum: -1,
              cellEdit: true,
              cellsubmit: 'remote',
              cellurl: './event_handlers/updateAnnotationCell.php',
              scrollOffset: 20,
              sortable: true,
	      pager: jQuery('#pager1'), 
	      sortname: 'id', 
	      viewrecords: true,
	      sortorder: "desc",
	      caption:"Annotations", 
 	      loadonce:true,
           }).navGrid('#pager1',{add:false,del:false});
           // end jQuery("#list1").jqgrid(defs).navGrid()

           jQuery("#annotator1").jqGrid(
           {  url:'getThread.php?file=1&thread=1&annotator=1',
              datatype: "json",
              colNames:
                 ['Post ID','Timestamp', 'User', 'Content','Parent','Relation'],
              colModel:
                 [{name:'Post ID',index:'postnum', width:postWidth,}, 
                  {name:'Timestamp',index:'timestamp', width:timestampWidth},
                  {name:'User',index:'user', width:userWidth},
                  {name:'Content',index:'content', width:300, 
                        formatter:colorThread, classes:"contentThread"},
                  {name:'Parent',index:'parent', width:postWidth, 
                        editable:true, edittype:'text'},
                  {name:'Relation',index:'relation', width:relationWidth,
                        align:"right", editable:true, edittype:'text'},],
              onSelectRow: 
                 function(idv)
                 {  var id = idv.split("-")[0];
                    if(id && id!==lastsela)
                    {  jQuery('#annotator1').restoreRow(lastsel);
                       //jQuery('#annotator1').editRow(id,true);
		       var graphHeight = 
                          jQuery('#list1').getGridParam('height');
		       var rowTop = 
                          jQuery('#list1 #'+id).position()['top']-graphHeight/2;
		       jQuery('#gbox_list1 .ui-jqgrid-bdiv').scrollTop(rowTop);
                       lastsel=idv;
                    }
                 },
	      afterInsertRow: 
                 function(idv)  
                 {  if(!(curPosts === undefined)) 
                    {  var id = idv.split("-")[0];
             	       if(jQuery.inArray(id, curPosts) > -1) 
                       {  if(id == lastsel) 
                          {  jQuery('#annotator1').jqGrid('setRowData',
                                 idv, 'false', "selected");
                          } 
		       } 
                       else 
                       {  jQuery('#annotator1').jqGrid('setRowData', 
                             idv, 'false', "highlight");
                       }
		    }
                 },
              height: threadHeight,
              rowNum: -1,
              scrollOffset: 20,
              sortable: true,
              sortname: 'id',
              viewrecords: true,
              isortorder: "desc",
              caption:"Annotator 1",
           });
           // end jQuery("#annotator1").jqGrid(

           function colorThread(cell, options, rowArr) 
           {  // if(rowArr[2] == 1) 
              // { }
              return cell;
           }
        });
        // end jQuery().ready()

</script>
</head>

<body>

<form id="selector" name="selector" action="editAnnotations.php" method="get">
	<select name="fileSel" id="fileSel"></select>
	<select name="annotator1Sel" id="annotator1Sel"></select>
	<INPUT type="submit" value="Send"> <INPUT type="reset">
</form>

<table id="list1"></table> <div id="pager1"></div>

<table id="container">
<tr>
<td><table id="annotator1"></table></td>

</tr>
</table>
</body>
</html> 
